# Sustainable Office Designer
# by Fabian Ritter <Fabian.Ritter@live.de>, 2012

require("SOD/tools/OpenStudio/Collection")

module SOD
  
  class SketchInfoContainer
    
    attr_accessor :footprintLength, :footprintWidth
    attr_accessor :pointOfOrigin, :direction
    attr_reader :footprintPoints, :update, :update_from_group
    
    def initialize
      @footprintLength = 0.0.m
      @footprintWidth = 0.0.m
      @pointOfOrigin = Geom::Point3d.new
      @direction = Geom::Vector3d.new
      @footprintPoints = Collection.new
    end
    
    def setFootprintPoints( pts )
      @footprintPoints.clear
      pts.each { |p| @footprintPoints.add p }
      
      UI.messagebox("Number of Points sent to SketchInfoContainer: " + @footprintPoints.length.to_s ) if $debug
    end
    
    def update( pts )
      setFootprintPoints( pts )
      
      vec1 = (@footprintPoints[1] - @footprintPoints[0])
      vec2 = (@footprintPoints[2] - @footprintPoints[1])
      
      clockwise = self.clockwise?(vec1, vec2)
      
      dist1 = vec1.length
      dist2 = vec2.length
      
      if (dist1 > dist2)
        @footprintLength = dist1
        @footprintWidth = dist2
        if clockwise
          @pointOfOrigin = @footprintPoints[1]
          @direction = vec1.normalize!.reverse!
        else
          @pointOfOrigin = @footprintPoints[0]
          @direction = vec1.normalize!
        end
        puts "SIC.update: 1st Option" if $debug
      else
        @footprintLength = dist2
        @footprintWidth = dist1
        if clockwise
          @pointOfOrigin = @footprintPoints[2]
          @direction = vec2.normalize!.reverse!
        else
          @pointOfOrigin = @footprintPoints[1]
          @direction = vec2.normalize!
        end
        puts "SIC.update: 2nd Option" if $debug
      end
      UI.messagebox "origin: " + @pointOfOrigin.to_s if $debug
      UI.messagebox "direction: " + @direction.to_s if $debug
      UI.messagebox "length: " + @footprintLength.to_s if $debug
      UI.messagebox "width: " + @footprintWidth.to_s if $debug
      
    end
    
    def clockwise?(vector1, vector2)
      cross = vector1 * vector2
      if cross.z > 0
        return false
      else
        return true
      end
    end
    
    def update_from_group( group )
      pts = []
      tr = group.transformation
      bbox = group.local_bounds
      
      UI.messagebox "transformation = " + tr.inspect if $debug
      
      0.upto(3) { |i| pts << bbox.corner( i ).transform( tr ) }
      pts[2], pts[3] = pts[3], pts[2] #to get the points in the right order...
      
      UI.messagebox "BB points: " + pts.inspect
      update( pts )
      
    end
    
  end
  
end
